package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.Result;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<String> getCode(User user, HttpSession session) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("手机号:{}的验证码为{}", phone, code);
            // 将验证码保存到redis缓存中,并且设置过期时间为5分钟
            stringRedisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.success("验证码获取成功");
        }
        return Result.error("验证码获取失败");
    }

    @Override
    public Result<User> login(Map map, HttpSession session) {
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        // 从redis缓存中获取验证码
        String codeInRedis = stringRedisTemplate.opsForValue().get(phone);
        if (codeInRedis != null && codeInRedis.equals(code)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userMapper.selectOne(queryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userMapper.insert(user);
            }
            session.setAttribute("userId", user.getId());
            // 登录成功则删除redis缓存中的验证码
            stringRedisTemplate.delete(phone);
            return Result.success(user);
        }
        return Result.error("登录失败");
    }
}
